package com.parking.status.sync.netty.service;

import com.parking.status.sync.entity.CommandBase;
import com.parking.status.sync.netty.entity.RequestPre;
import com.parking.status.sync.netty.entity.ResponsePre;
import com.parking.status.sync.netty.entity.ResultCode;
import com.parking.status.sync.netty.event.RequestReceivedEvent;
import com.parking.status.sync.netty.event.RequestReceivedEventParameters;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2015/9/18.
 */
@Component
public class RequestReceivedEventListener implements ApplicationListener<RequestReceivedEvent> {

    @Autowired
    ResponseFactory responseFactory;

    @Autowired
    CommandFactory commandFactory;

    @Override
    public void onApplicationEvent(RequestReceivedEvent requestReceivedEvent) {

        //根据请求发送回复
        RequestReceivedEventParameters param = (RequestReceivedEventParameters)requestReceivedEvent.getSource();
        RequestPre request = param.getRequest();
        ChannelHandlerContext context = param.getContext();

        //保存入库
        CommandBase command = commandFactory.createCommand(request);
        commandFactory.saveCommand(command);

        //发送回复
        ResponsePre response = responseFactory.createResponse(
                request.getSeqno(), request.getCode(), ResultCode.RESULT_OK);
        context.channel().writeAndFlush(response);
    }
}
